package com.roy.royminidao.common.framework.lang.db;

import com.roy.royminidao.common.framework.lang.entity.Entity;
import com.roy.royminidao.common.framework.lang.web.page.Page;

import java.util.List;

import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;

/**
 * 
 * sql模板<br>
 * sql模板
 * 
 * @author rong
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class SqlSessionExecutor extends SqlSessionTemplate {

	/**
	 * 构造函数
	 * 
	 * @param sqlSessionFactory
	 */
	public SqlSessionExecutor(SqlSessionFactory sqlSessionFactory) {
		super(sqlSessionFactory);
	}

	/**
	 * 根据分页条件，查询结果集
	 * 
	 * @param statement
	 * @param parameter
	 * @param rowBounds
	 * @param limit
	 * @return
	 */
	public List<? extends Entity> selectPage(String statement, Object parameter, Page page) {

		// 设置符合条件的结果集总数
		List<Entity> resultForCount = super.selectList(statement, parameter, new RowBounds(-1, -1));

		Integer resultCount = ((Entity) resultForCount.get(0)).getTotalCount();
		int totalCount = resultCount.intValue();
		page.setTotalRecords(totalCount);

		int offset = page.getRowStart();
		int pageSize = page.getPageSize();

		RowBounds bound = null;
		if (totalCount < (offset + pageSize)) {
			bound = new RowBounds(offset, totalCount - offset);
		} else {
			bound = new RowBounds(offset, pageSize);
		}

		// 查询分页内容
		List<? extends Entity> resultList = selectList(statement, parameter, bound);

		return resultList;
	}
}
